package com.kld.shop.controller.admin;

import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.util.EncryptionUtil;
import com.kld.common.util.FileUpload;
import com.kld.common.util.VerifyCodeUtils;
import com.kld.shop.controller.base.BaseController;
import com.kld.sys.api.ISysUserService;
import com.kld.sys.po.SysUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//import java.util.regex.Pattern;

@Controller
@RequestMapping({"/admin","/admin/home"})
public class HomeController extends BaseController {
    
    static final Log LOG = LogFactory.getLog(HomeController.class);

    @Autowired
    private ISysUserService iSysUserService;
//
//    @Resource
//    JDService jdService;
    @RequestMapping("/errlogin")
    public ModelAndView errlogin(HttpServletRequest request, HttpServletResponse response)
    {
        ModelMap result = new ModelMap();
        String msg = request.getParameter("msg");
        ArrayList<String> list = new ArrayList<>();
        result.put("msg", msg);
        result.put("list", list);
        return new ModelAndView("/admin/index",result);
    }

    @RequestMapping("/login")
    public ModelAndView Login(HttpServletRequest request, HttpServletResponse response)
    {
        ModelMap result = new ModelMap();
        String msg = request.getParameter("msg");
        result.put("msg", msg);
        return new ModelAndView("admin/login",result);
    }


    @RequestMapping("loginerror")
    public ModelAndView LoginError()
    {
        ModelMap result = new ModelMap();
        result.put("msg", "登录失败！用户名或密码有误");
        return new ModelAndView("admin/login",result);
    }
    
    @ResponseBody
    @RequestMapping("message")
    public  String message(HttpServletRequest request,HttpServletResponse response)
    {
        return request.getParameter("msg");
    }

    @RequestMapping({"","/","/index"})
    public  ModelAndView Index()
    {

        ArrayList<String> list =   GetUserFuncList();

        return new ModelAndView("admin/index","list",list);
        // return "admin/index";
    }

    @RequestMapping("generateVerifyCode")
    public void generateVerifyCode(){
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //存入会话session
        HttpSession session = request.getSession(true);
        session.setAttribute("rand", verifyCode.toLowerCase());
        //生成图片
        int w = 200, h = 80;
        try {
            VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
        }catch (IOException ex){
            logger.error("验证码生成图片异常！"+ex);
        }
    }

    /**
     * 修改密码
     * @param pwd
     * @param newpwd
     * @return
     */
    @ResponseBody()
    @RequestMapping("modifyPwd")
    public ResultMsg updatePwd(String pwd, String newpwd){
        String username = getUserDetails().getUsername();
        ResultMsg rmsg = new ResultMsg();
        SysUser user = iSysUserService.querySysUserByUserName(username);
//        Pattern patt = Pattern.compile("/^[@A-Za-z0-9!#$%^&*.~]{6,22}$/");
        if(user==null){
            rmsg.setResult(false);
            rmsg.setMsg("用户名不存在");
            return rmsg;
        }
        if(! user.getPwd().equals(EncryptionUtil.MD5(pwd).toLowerCase())){
            rmsg.setResult(false);
            rmsg.setMsg("原始密码有误");
            return rmsg;
        }else if(user.getPwd().equals(EncryptionUtil.MD5(newpwd).toLowerCase())){
            rmsg.setResult(false);
            rmsg.setMsg("新密码与原始密码一样，操作失败");
            return rmsg;
        }

        user.setPwd(EncryptionUtil.MD5(newpwd).toLowerCase());
        try {
            int upd = iSysUserService.update(user);
            if(upd>0){
                rmsg.setResult(true);
                rmsg.setMsg("修改密码成功！");
                return rmsg;
            }
        }catch (Exception ex){

            rmsg.setResult(false);
            rmsg.setMsg("发生异常，请重试");
            return rmsg;
        }
        return rmsg;
    }

    @ResponseBody()
    @RequestMapping(value="uploadFile",method = RequestMethod.POST)
    public String FileUpload(MultipartFile file){
        JSONObject obj = new JSONObject();
        String[] filepaths ={"fromeditor"};
        List<String> paths = FileUpload.Upload(request, filepaths);
        if(paths==null || paths.size()==0){

            obj.put("error", 1);
            obj.put("message", "上传失败");
        } else {

            obj.put("error",0);
            obj.put("url",paths.get(0));
        }

        return obj.toString();
    }
//
//    @ResponseBody()
//    @RequestMapping(value = "getProvinceList",method = RequestMethod.GET)
//    public JSONArray getProvinceList(){
//        JSONArray jsonArray = JSONArray.fromObject(jdService.getProvince().getData());
//        return jsonArray;
//    }
//
//    @ResponseBody()
//    @RequestMapping(value = "getCityList",method = RequestMethod.GET)
//    public JSONArray getCityList(Integer pid){
//        JSONArray jsonArray = JSONArray.fromObject(jdService.getCity(pid).getData());
//        return jsonArray;
//    }
//    @ResponseBody()
//    @RequestMapping(value = "getCountyList",method = RequestMethod.GET)
//    public JSONArray getCountyList(Integer cid){
//        JSONArray jsonArray = JSONArray.fromObject(jdService.getCounty(cid).getData());
//        return jsonArray;
//    }
//    @ResponseBody()
//    @RequestMapping(value = "getTownList",method = RequestMethod.GET)
//    public JSONArray getTownList(Integer ctid){
//        JSONArray jsonArray = JSONArray.fromObject(jdService.getTown(ctid).getData());
//        return jsonArray;
//    }
}


